import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';

/// Created by XieXin on 2020/3/18.
/// 打印日志
class LoggingInterceptor extends Interceptor {
  late DateTime startTime, endTime;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    startTime = DateTime.now();
    LogUtil.v("=========Request=========>>");
    if (options.queryParameters.isEmpty) {
      LogUtil.v("request url: ${options.baseUrl}${options.path}");
    } else {
      LogUtil.v(
          ">> request url: ${options.baseUrl}${options.path}?${Transformer.urlEncodeMap(options.queryParameters)}");
    }
    LogUtil.v(">> request method: ${options.method}");
    LogUtil.v(">> request headers: ${options.headers.toString()}");
    LogUtil.v(">> request ContentType: ${options.contentType}");
    if (options.data is FormData) {
      FormData data = options.data;
      LogUtil.v(">> request data length: ${data.length}");
      LogUtil.v(">> request data fields length: ${data.fields.length}");
      LogUtil.v(">> request data fields : ${data.fields.toString()}");
      LogUtil.v(">> request data files length: ${data.files.length}");
      LogUtil.v(">> request data files boundary: ${data.boundary}");
      LogUtil.v(">> request data files isFinalized: ${data.isFinalized}");
    } else {
      LogUtil.v(">> request data: ${options.data.toString()}");
    }
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    endTime = DateTime.now();
    int duration = endTime.difference(startTime).inMilliseconds;
    LogUtil.v(
        "<<=========Response statusCode: ${response.statusCode}=========");
    if (response.requestOptions.queryParameters.isEmpty) {
      LogUtil.v(
          "<< response url: ${response.requestOptions.baseUrl}${response.requestOptions.path}");
    } else {
      LogUtil.v(
          "<< response url: ${response.requestOptions.baseUrl}${response.requestOptions.path}?${Transformer.urlEncodeMap(response.requestOptions.queryParameters)}");
    }
    LogUtil.v("<< response method: ${response.requestOptions.method}");
    LogUtil.v("<< response headers: ${response.headers.toString()}");
    LogUtil.v("<< response data: ${response.data.toString()}");
    LogUtil.v('<<=========End: $duration 毫秒=========');
    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    LogUtil.e('=========Error=========');
    LogUtil.e('error: ${err.message}');
    super.onError(err, handler);
  }
}
